package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Category;
import com.itheima.service.CatergoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @email 1572178030@qq.com
 * @author:黄海宾
 * @date: 2023/2/7  15:19
 */

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CatergoryService catergoryService;

    //分类分页查询
    @GetMapping("/page")
    public R<Page> pagination(int page, int pageSize) {
        Page<Category> categoryPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Category::getSort);

        Page<Category> page1 = catergoryService.page(categoryPage, queryWrapper);
        return R.success(page1);

    }

    //新增分类
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        boolean save = catergoryService.save(category);
        if (save) {
            return R.success("添加成功");
        }
        return R.success("添加失败");
    }

    //删除分类
    @DeleteMapping
    public R<String> delete(Long id) {
        log.info("删除分类，id为：{}", id);
        catergoryService.remove(id);
        //因为相关联，看是否可以直接删除
        return R.success("删除成功");
    }

    //修改
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        catergoryService.updateById(category);
        return R.success("修改成功");
    }

    /*    @GetMapping("/list")//不能用对象接收
        public R<List<Category>> list( Category category) {
            log.info("查到的数据category{}", category);
            //查找Category中的type
            LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(category!=null,Category::getType, category.getType());

            List<Category> list = catergoryService.list(queryWrapper);
            log.info("查到的数据category{}", list);
            return R.success(list);
        }*/
    @GetMapping("/list")
    public R<List<Category>> list(Integer type) {
        //查找Category中的type
        // select * from category where type = #{type}
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(type != null, Category::getType, type);

        List<Category> list = catergoryService.list(queryWrapper);
        log.info("查到的数据{}", list);
        return R.success(list);
    }
}
